package com.foxsteps.gsonformat.manager;

import com.foxsteps.gsonformat.constants.ApiDocConstant;
import com.foxsteps.gsonformat.enums.MapstructModeEnum;
import com.foxsteps.gsonformat.helper.DialogHelper;
import com.foxsteps.gsonformat.model.DialogModel;
import com.foxsteps.gsonformat.ui.MapstructDialog;
import com.google.common.collect.Lists;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilBase;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * @author dongxuanliang252
 * @date 2018-12-18 12:05
 */
public class ApiDocActionManger {

    public static List<String> FILTER_FIELD = Lists.newArrayList("traceId","createdBy",
            "creationDate","updatedBy","updationDate","enabledFlag");

    public void showDialog(AnActionEvent e, Integer mode) {
        PsiElement psiElement = e.getData(LangDataKeys.PSI_ELEMENT);
        if (psiElement instanceof PsiMethod) {
            PsiMethod psiMethod = (PsiMethod) psiElement;
            DialogModel newDialogModel = DialogHelper.INSTANCE.createNewDialogModel(psiMethod);
            newDialogModel.setMode(mode);
            if(MapstructModeEnum.DEMO.getCode().equals(mode)){
                showMapStructDialog(e,newDialogModel,psiElement);
            }else {
                DialogHelper.INSTANCE.writeJavaDoc(newDialogModel, psiElement);
            }
        } else {
            Messages.showWarningDialog(ApiDocConstant.NOTIFICATION_FOCUS_CONTENT, ApiDocConstant.NOTIFICATION_TITLE);
        }
    }

    private void showMapStructDialog(AnActionEvent event, DialogModel newDialogModel, PsiElement psiElement) {
        Project project = event.getData(PlatformDataKeys.PROJECT);
        Editor editor = event.getData(PlatformDataKeys.EDITOR);
        PsiFile mFile = PsiUtilBase.getPsiFileInEditor(editor, project);
        PsiClass psiClass = getTargetClass(editor, mFile);
        //初始化Json弹框
        MapstructDialog jsonD = new MapstructDialog(psiClass, mFile, project,newDialogModel,psiElement);
        jsonD.setClass(psiClass);
        jsonD.setFile(mFile);
        jsonD.setProject(project);
        jsonD.setSize(1000, 700);
        jsonD.setLocationRelativeTo(null);
        jsonD.setVisible(true);
    }

    @Nullable
    protected PsiClass getTargetClass (Editor editor, PsiFile file) {
        int offset = editor.getCaretModel().getOffset();
        PsiElement element = file.findElementAt(offset);
        if (element == null) return null;
        final PsiClass target = PsiTreeUtil.getParentOfType(element, PsiClass.class);
        return target instanceof SyntheticElement ? null : target;
    }
}
